<template>
  <div class="system-monitoring">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>系统监控</h1>
      <p>实时监控系统状态和性能指标</p>
    </div>

    <!-- 实时状态卡片 -->
    <div class="status-cards">
      <div class="status-card" :class="{ warning: cpuUsage > 80, danger: cpuUsage > 90 }">
        <div class="card-icon cpu-icon">
          <i class="el-icon-cpu"></i>
        </div>
        <div class="card-content">
          <h3>{{ cpuUsage }}%</h3>
          <p>CPU使用率</p>
          <el-progress :percentage="cpuUsage" :color="getProgressColor(cpuUsage)" />
        </div>
      </div>

      <div class="status-card" :class="{ warning: memoryUsage > 80, danger: memoryUsage > 90 }">
        <div class="card-icon memory-icon">
          <i class="el-icon-folder"></i>
        </div>
        <div class="card-content">
          <h3>{{ memoryUsage }}%</h3>
          <p>内存使用率</p>
          <el-progress :percentage="memoryUsage" :color="getProgressColor(memoryUsage)" />
        </div>
      </div>

      <div class="status-card" :class="{ warning: diskUsage > 80, danger: diskUsage > 90 }">
        <div class="card-icon disk-icon">
          <i class="el-icon-files"></i>
        </div>
        <div class="card-content">
          <h3>{{ diskUsage }}%</h3>
          <p>磁盘使用率</p>
          <el-progress :percentage="diskUsage" :color="getProgressColor(diskUsage)" />
        </div>
      </div>

      <div class="status-card">
        <div class="card-icon network-icon">
          <i class="el-icon-connection"></i>
        </div>
        <div class="card-content">
          <h3>{{ networkSpeed }}</h3>
          <p>网络速度</p>
          <div class="network-info">
            <span>↑ {{ uploadSpeed }}</span>
            <span>↓ {{ downloadSpeed }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 监控图表 -->
    <div class="monitoring-charts">
      <div class="chart-container">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>系统性能趋势</span>
              <el-button type="text" @click="refreshCharts">
                <i class="el-icon-refresh"></i>
                刷新
              </el-button>
            </div>
          </template>
          <div ref="performanceChart" class="chart"></div>
        </el-card>
      </div>

      <div class="chart-container">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>服务状态监控</span>
              <el-button type="text" @click="refreshServiceStatus">
                <i class="el-icon-refresh"></i>
                刷新
              </el-button>
            </div>
          </template>
          <div class="service-status">
            <div class="service-item" v-for="service in services" :key="service.name">
              <div class="service-info">
                <div class="service-name">{{ service.name }}</div>
                <div class="service-description">{{ service.description }}</div>
              </div>
              <div class="service-indicator">
                <el-tag 
                  :type="service.status === 'running' ? 'success' : 'danger'"
                  size="small"
                >
                  {{ service.status === 'running' ? '运行中' : '已停止' }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 系统信息 -->
    <div class="system-info-section">
      <div class="info-left">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>系统信息</span>
              <el-button type="text" @click="refreshSystemInfo">
                <i class="el-icon-refresh"></i>
                刷新
              </el-button>
            </div>
          </template>
          <div class="info-grid">
            <div class="info-item">
              <div class="info-label">操作系统</div>
              <div class="info-value">{{ systemInfo.os }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">CPU型号</div>
              <div class="info-value">{{ systemInfo.cpu }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">内存容量</div>
              <div class="info-value">{{ systemInfo.memory }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">磁盘容量</div>
              <div class="info-value">{{ systemInfo.disk }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">启动时间</div>
              <div class="info-value">{{ systemInfo.startTime }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">运行时间</div>
              <div class="info-value">{{ systemInfo.uptime }}</div>
            </div>
          </div>
        </el-card>
      </div>

      <div class="info-right">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>实时日志</span>
              <div class="header-actions">
                <el-button type="text" @click="clearLogs">
                  <i class="el-icon-delete"></i>
                  清空
                </el-button>
                <el-button type="text" @click="exportLogs">
                  <i class="el-icon-download"></i>
                  导出
                </el-button>
              </div>
            </div>
          </template>
          <div class="logs-container">
            <div 
              class="log-item"
              v-for="log in logs"
              :key="log.id"
              :class="log.level"
            >
              <div class="log-time">{{ log.time }}</div>
              <div class="log-level">{{ log.level.toUpperCase() }}</div>
              <div class="log-message">{{ log.message }}</div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 告警配置 -->
    <div class="alert-section">
      <el-card class="alert-card">
        <template #header>
          <div class="card-header">
            <span>告警配置</span>
            <el-button type="primary" @click="showAlertDialog">
              <i class="el-icon-plus"></i>
              添加告警
            </el-button>
          </div>
        </template>
        <el-table :data="alertRules" style="width: 100%">
          <el-table-column prop="name" label="规则名称" />
          <el-table-column prop="metric" label="监控指标" />
          <el-table-column prop="condition" label="触发条件" />
          <el-table-column prop="threshold" label="阈值" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="true"
                :inactive-value="false"
                @change="toggleAlertRule(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button type="text" @click="editAlertRule(scope.row)">
                编辑
              </el-button>
              <el-button type="text" @click="deleteAlertRule(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 告警规则对话框 -->
    <el-dialog
      v-model="alertDialogVisible"
      :title="isEditAlertMode ? '编辑告警规则' : '添加告警规则'"
      width="500px"
    >
      <el-form
        :model="alertForm"
        :rules="alertFormRules"
        ref="alertFormRef"
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="alertForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="监控指标" prop="metric">
          <el-select v-model="alertForm.metric" placeholder="请选择监控指标">
            <el-option label="CPU使用率" value="cpu" />
            <el-option label="内存使用率" value="memory" />
            <el-option label="磁盘使用率" value="disk" />
            <el-option label="网络延迟" value="network" />
          </el-select>
        </el-form-item>
        <el-form-item label="触发条件" prop="condition">
          <el-select v-model="alertForm.condition" placeholder="请选择触发条件">
            <el-option label="大于" value="gt" />
            <el-option label="小于" value="lt" />
            <el-option label="等于" value="eq" />
          </el-select>
        </el-form-item>
        <el-form-item label="阈值" prop="threshold">
          <el-input-number
            v-model="alertForm.threshold"
            :min="0"
            :max="100"
            placeholder="请输入阈值"
          />
        </el-form-item>
        <el-form-item label="通知方式" prop="notificationMethod">
          <el-checkbox-group v-model="alertForm.notificationMethod">
            <el-checkbox label="email">邮件</el-checkbox>
            <el-checkbox label="sms">短信</el-checkbox>
            <el-checkbox label="webhook">Webhook</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="alertDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAlertRule">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

export default {
  name: 'SystemMonitoring',
  setup() {
    const performanceChart = ref(null)
    const alertDialogVisible = ref(false)
    const isEditAlertMode = ref(false)
    const alertFormRef = ref(null)
    let chart = null
    let updateInterval = null

    // 性能数据
    const cpuUsage = ref(45)
    const memoryUsage = ref(62)
    const diskUsage = ref(34)
    const networkSpeed = ref('125 Mbps')
    const uploadSpeed = ref('23 Mbps')
    const downloadSpeed = ref('102 Mbps')

    // 系统信息
    const systemInfo = ref({
      os: 'Ubuntu 20.04 LTS',
      cpu: 'Intel Core i7-10700K',
      memory: '16GB DDR4',
      disk: '1TB SSD',
      startTime: '2025-01-01 09:00:00',
      uptime: '15天 6小时 30分钟'
    })

    // 服务状态
    const services = ref([
      { name: 'Web服务', description: 'Nginx Web服务器', status: 'running' },
      { name: '数据库', description: 'MySQL数据库服务', status: 'running' },
      { name: 'Redis缓存', description: 'Redis缓存服务', status: 'running' },
      { name: '消息队列', description: 'RabbitMQ消息队列', status: 'running' },
      { name: 'AI模型服务', description: 'AI推理服务', status: 'running' },
      { name: '文件服务', description: '文件存储服务', status: 'stopped' }
    ])

    // 系统日志
    const logs = ref([
      { id: 1, time: '2025-01-15 10:30:00', level: 'info', message: '系统启动成功' },
      { id: 2, time: '2025-01-15 10:31:00', level: 'info', message: '用户登录：admin' },
      { id: 3, time: '2025-01-15 10:32:00', level: 'warning', message: 'CPU使用率超过80%' },
      { id: 4, time: '2025-01-15 10:33:00', level: 'error', message: '文件服务连接失败' },
      { id: 5, time: '2025-01-15 10:34:00', level: 'info', message: '数据库备份完成' }
    ])

    // 告警规则
    const alertRules = ref([
      { id: 1, name: 'CPU高使用率告警', metric: 'cpu', condition: 'gt', threshold: 80, status: true },
      { id: 2, name: '内存不足告警', metric: 'memory', condition: 'gt', threshold: 85, status: true },
      { id: 3, name: '磁盘空间不足', metric: 'disk', condition: 'gt', threshold: 90, status: false }
    ])

    // 告警表单
    const alertForm = reactive({
      id: null,
      name: '',
      metric: '',
      condition: '',
      threshold: 0,
      notificationMethod: []
    })

    // 表单验证规则
    const alertFormRules = {
      name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
      metric: [{ required: true, message: '请选择监控指标', trigger: 'change' }],
      condition: [{ required: true, message: '请选择触发条件', trigger: 'change' }],
      threshold: [{ required: true, message: '请输入阈值', trigger: 'blur' }]
    }

    // 获取进度条颜色
    const getProgressColor = (percentage) => {
      if (percentage > 90) return '#f56c6c'
      if (percentage > 80) return '#e6a23c'
      if (percentage > 60) return '#409eff'
      return '#67c23a'
    }

    // 初始化图表
    const initChart = () => {
      if (!performanceChart.value) return

      chart = echarts.init(performanceChart.value)
      
      const option = {
        title: {
          text: '系统性能监控',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['CPU使用率', '内存使用率', '磁盘使用率']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: 'CPU使用率',
            type: 'line',
            stack: '总量',
            data: []
          },
          {
            name: '内存使用率',
            type: 'line',
            stack: '总量',
            data: []
          },
          {
            name: '磁盘使用率',
            type: 'line',
            stack: '总量',
            data: []
          }
        ]
      }

      chart.setOption(option)
      
      // 模拟实时数据更新
      updateChartData()
    }

    // 更新图表数据
    const updateChartData = () => {
      if (!chart) return

      const now = new Date()
      const timeStr = now.toLocaleTimeString()
      
      const option = chart.getOption()
      
      // 添加新数据点
      option.xAxis[0].data.push(timeStr)
      option.series[0].data.push(cpuUsage.value)
      option.series[1].data.push(memoryUsage.value)
      option.series[2].data.push(diskUsage.value)
      
      // 保持最多20个数据点
      if (option.xAxis[0].data.length > 20) {
        option.xAxis[0].data.shift()
        option.series[0].data.shift()
        option.series[1].data.shift()
        option.series[2].data.shift()
      }
      
      chart.setOption(option)
    }

    // 更新系统数据
    const updateSystemData = () => {
      cpuUsage.value = Math.floor(Math.random() * 100)
      memoryUsage.value = Math.floor(Math.random() * 100)
      diskUsage.value = Math.floor(Math.random() * 100)
      
      // 添加新日志
      const newLog = {
        id: Date.now(),
        time: new Date().toLocaleString(),
        level: ['info', 'warning', 'error'][Math.floor(Math.random() * 3)],
        message: `系统状态检查：CPU ${cpuUsage.value}%, 内存 ${memoryUsage.value}%`
      }
      logs.value.unshift(newLog)
      
      // 保持最多100条日志
      if (logs.value.length > 100) {
        logs.value.pop()
      }
      
      updateChartData()
    }

    // 刷新图表
    const refreshCharts = () => {
      updateSystemData()
      ElMessage.success('图表已刷新')
    }

    // 刷新服务状态
    const refreshServiceStatus = () => {
      ElMessage.success('服务状态已刷新')
    }

    // 刷新系统信息
    const refreshSystemInfo = () => {
      ElMessage.success('系统信息已刷新')
    }

    // 清空日志
    const clearLogs = () => {
      ElMessageBox.confirm('确定要清空所有日志吗？')
        .then(() => {
          logs.value = []
          ElMessage.success('日志已清空')
        })
        .catch(() => {})
    }

    // 导出日志
    const exportLogs = () => {
      ElMessage.success('日志导出成功')
    }

    // 显示告警对话框
    const showAlertDialog = () => {
      isEditAlertMode.value = false
      resetAlertForm()
      alertDialogVisible.value = true
    }

    // 编辑告警规则
    const editAlertRule = (rule) => {
      isEditAlertMode.value = true
      Object.assign(alertForm, rule)
      alertDialogVisible.value = true
    }

    // 删除告警规则
    const deleteAlertRule = (rule) => {
      ElMessageBox.confirm(`确定要删除告警规则 ${rule.name} 吗？`)
        .then(() => {
          const index = alertRules.value.findIndex(r => r.id === rule.id)
          if (index !== -1) {
            alertRules.value.splice(index, 1)
            ElMessage.success('告警规则删除成功')
          }
        })
        .catch(() => {})
    }

    // 切换告警规则状态
    const toggleAlertRule = (rule) => {
      const status = rule.status ? '启用' : '禁用'
      ElMessage.success(`告警规则${status}成功`)
    }

    // 重置告警表单
    const resetAlertForm = () => {
      Object.assign(alertForm, {
        id: null,
        name: '',
        metric: '',
        condition: '',
        threshold: 0,
        notificationMethod: []
      })
      if (alertFormRef.value) {
        alertFormRef.value.resetFields()
      }
    }

    // 保存告警规则
    const saveAlertRule = () => {
      alertFormRef.value.validate((valid) => {
        if (valid) {
          if (isEditAlertMode.value) {
            // 编辑告警规则
            const index = alertRules.value.findIndex(r => r.id === alertForm.id)
            if (index !== -1) {
              alertRules.value[index] = { ...alertForm }
              ElMessage.success('告警规则更新成功')
            }
          } else {
            // 添加告警规则
            const newRule = {
              ...alertForm,
              id: Date.now(),
              status: true
            }
            alertRules.value.push(newRule)
            ElMessage.success('告警规则添加成功')
          }
          alertDialogVisible.value = false
          resetAlertForm()
        }
      })
    }

    onMounted(() => {
      initChart()
      
      // 设置定时更新
      updateInterval = setInterval(updateSystemData, 5000)
    })

    onUnmounted(() => {
      if (updateInterval) {
        clearInterval(updateInterval)
      }
      if (chart) {
        chart.dispose()
      }
    })

    return {
      performanceChart,
      alertDialogVisible,
      isEditAlertMode,
      alertFormRef,
      cpuUsage,
      memoryUsage,
      diskUsage,
      networkSpeed,
      uploadSpeed,
      downloadSpeed,
      systemInfo,
      services,
      logs,
      alertRules,
      alertForm,
      alertFormRules,
      getProgressColor,
      refreshCharts,
      refreshServiceStatus,
      refreshSystemInfo,
      clearLogs,
      exportLogs,
      showAlertDialog,
      editAlertRule,
      deleteAlertRule,
      toggleAlertRule,
      resetAlertForm,
      saveAlertRule
    }
  }
}
</script>

<style scoped>
.system-monitoring {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 16px;
  color: #666;
}

.status-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.status-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e6e6e6;
  transition: all 0.3s ease;
}

.status-card.warning {
  border-color: #e6a23c;
  background: #fdf6ec;
}

.status-card.danger {
  border-color: #f56c6c;
  background: #fef0f0;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: #fff;
}

.cpu-icon {
  background: linear-gradient(45deg, #409eff, #66d9ef);
}

.memory-icon {
  background: linear-gradient(45deg, #67c23a, #95de64);
}

.disk-icon {
  background: linear-gradient(45deg, #e6a23c, #ffd666);
}

.network-icon {
  background: linear-gradient(45deg, #f56c6c, #ff9c6e);
}

.card-content {
  flex: 1;
}

.card-content h3 {
  font-size: 28px;
  color: #333;
  margin-bottom: 5px;
}

.card-content p {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.network-info {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #999;
}

.monitoring-charts {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.chart-container {
  height: 400px;
}

.chart-card {
  height: 100%;
}

.chart {
  height: 320px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.service-status {
  height: 320px;
  overflow-y: auto;
}

.service-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.service-item:last-child {
  border-bottom: none;
}

.service-info {
  flex: 1;
}

.service-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.service-description {
  font-size: 12px;
  color: #666;
}

.system-info-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.info-card {
  height: 400px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-label {
  font-size: 12px;
  color: #999;
}

.info-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.logs-container {
  height: 320px;
  overflow-y: auto;
  font-family: monospace;
}

.log-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 12px;
}

.log-item.info {
  background: #f0f9ff;
}

.log-item.warning {
  background: #fef0e6;
}

.log-item.error {
  background: #fef0f0;
}

.log-time {
  width: 150px;
  color: #666;
  flex-shrink: 0;
}

.log-level {
  width: 80px;
  font-weight: 500;
  flex-shrink: 0;
}

.log-message {
  flex: 1;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.alert-section {
  margin-bottom: 20px;
}

.alert-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .monitoring-charts {
    grid-template-columns: 1fr;
  }
  
  .system-info-section {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .status-cards {
    grid-template-columns: 1fr;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style> 